import api from '../../../common/api.js'
import util from "../../../utils/util.js";
import p from '../../../utils/platform.js';
import { getActiveStr, formatDecimal, volidatePublishParams } from '../../../utils/utilsNew.js';
import { insertHouseLog } from '../../../common/log.js';
import constant from '../../../common/constant.js';
import { menuHandler } from '../../../common/menuHandler.js';
import { lightSpotType } from '../../../models/filterConfigs';
const computedBehavior = require('miniprogram-computed')

/*VR委托子类型（0：默认，1：VR）*/
// houSubType;
/*VR委托子类型状态（0：无，1：关联中，-1：关联失败，10：已完成）*/
// houSubTypeState;


var essentialInfo = {},
  houseInfo = {},
  recommendInfo = {}, //essentialInfo基本信息 houseInfo房源信息 recommendInfo房源介绍信息
  aar = [];


const app = getApp()
Page({
  behaviors: [computedBehavior],
  /**
   * 页面的初始数据
   */
  data: {
    isCreatingBuilding: false, //正在创建新的房源委托
    lightSpotType: lightSpotType.map((v) => v.value),
    subscribeJumpTag: '',
    subscribeCityCode: '',
    isShowDialogSubscribe: false,
    subscribeName: '',
    subscribeId: '',
    hasSubscribeStatus: false,
    isSubscribe: false,
    subscribe: false, //是否是从新上房源列表过来的
    isScan: false, //是否是搬家过来的
    goCentre: false, //是否跳转到充值页面
    items: [
      {value: '下载房源的VR',checked: 'true'}
    ],
    releaseNumber: '',
    memberOption: false,
    sureDownVr: false, 
    overflow: "overflow:hidden",
    flag: 1,
    vrDown: true,
    vr: false,
    text: false, //判断textara是否隐藏，解决在安卓机上内容飘逸的问题
    houDelId: '',
    resblockId: null,
    hdResblockId: null,
    forbid: false, //是否禁止状态栏切换
    detailContent: '', //房源详情
    delegationType: '',
    userId: '',
    storeId: '',
    size: 4, //一行显示几张图片
    titleNum: 0,
    bottom: 0,
    tabHeaderList: [{
        text: "二手",
      },
      {
        text: "出租",
      },
      {
        text: "租售",
      }
    ],
    // currentTabHeaderIndex: null, //头部切换
    currentTabHeaderIndex: 2, //头部切换
    showDialog: false,
    locationState: 0, //当前弹窗显示
    addOwnerNum: 0, //新增页主列表数
    imgArray: [], //图片列表
    videoArray: [], //视频列表
    villageData: "", //初始化的数据,
    resblcok_all: [], //所有楼
    floor_all: [], //所有层，
    unit_all: [], //所有单元
    room_all: [],
    hdBuildingId: "",
    buildingId: "",
    unit: "",
    // 几栋 几单元 几层 几0几
    isResblcok: "",
    isUnit: "",
    isFloor: "",
    isRoom: "",
    zonglouceng: '',
    //室厅卫
    shi: "",
    ting: "",
    wei: "",
    //提户
    ti: "",
    hu: "",
    //面积
    area: "",
    //标题
    roomtitle: "",
    //售价
    salse: "",
    // 房源详情
    // 1. 房屋类型
    houseType: '',
    //2.产权
    chanquanType: '',
    loucenType: '', //楼层
    chaoxiangType: '', //朝向
    daikuanType: '',
    xueweiType: "",
    kanfangType: '',
    chushouType: [],
    lightSpot: [], //房源亮点
    chuzuType: [],
    //租金
    rentmoney: "",
    ya: "",
    fu: "",
    successModal: true,
    houseId: "",
    hdHouseId: "",
    successId: "",
    zhuangxiuType: "",
    salseFocus: false,
    rentFocus: false,
    areaFocus: false,
    floorNumberInputTime: null, //填写位置的延迟回到底部
    floorNumberInputCount: 0,
    backFromInputTextValuePageCb: null, //从页面回来的回调
    _houseTitle: "", //房源标题
    _sellPoint: "", //核心卖点
    _ownerState: "", //业主心态
    _service: "", //税费解析
    
    _houseType: "",
    _trafficResolve: "",
    _surroundMating: "",
    _decoration: "",
    _resblockIntroduce: "",
    
  },

  computed: {
    canPubilish(data) {
      const {
        area,
        salse,
        rentmoney,
        shi,
        ting,
        wei,
        currentTabHeaderIndex
      } = data
      let params = {
        area,
        shi,
        ting,
        wei,
      }
      switch (currentTabHeaderIndex) {
        case 0:
          params.salse = salse
          break
        case 1:
          params.rent = rentmoney
          break
        case 2:
          params.salse = salse
          params.rent = rentmoney
          break
      }
      Object.keys(params).forEach(key => {
        params[key] = String(params[key])
      })
      return volidatePublishParams(params)
    },
    $_houseTitle(data) {
      return getActiveStr(data._houseTitle, 30)
    },
    $_sellPoint(data) {
      return getActiveStr(data._sellPoint, 30)
    },
    $_ownerState(data) {
      return getActiveStr(data._ownerState, 30)
    },
    $_service(data) {
      return getActiveStr(data._service, 30)
    },
    $_houseType(data) {
      return getActiveStr(data._houseType, 30)
    },
    $_trafficResolve(data) {
      return getActiveStr(data._trafficResolve, 30)
    },
    $_surroundMating(data) {
      return getActiveStr(data._surroundMating, 30)
    },
    $_decoration(data) {
      return getActiveStr(data._decoration, 30)
    },
    $_resblockIntroduce(data) {
      return getActiveStr(data._resblockIntroduce, 30)
    },
  },

  // 键入房源标题
  handleHouseTitle() {
    app.globalData.inputTextValuePage = this.data._houseTitle
    p.navigateTo({
      url: `/pages/addHouse/inputTextValue/inputTextValue?placeholder=请输入房源标题&maxCount=30`
    })
    this.data.backFromInputTextValuePageCb = () => {
      // console.log("房源标题", app.globalData.inputTextValuePage);
      this.setData({
        _houseTitle: app.globalData.inputTextValuePage
      })
      app.globalData.inputTextValuePage = ""
    }
  },

  // 自定义推荐信息
  handleSetRecommend(e) {
    const {title, key} = e.currentTarget.dataset
    app.globalData.inputTextValuePage = this.data[key]
    p.navigateTo({
      url: `/pages/addHouse/inputTextValue/inputTextValue?placeholder=请输入${title}&maxCount=400`
    })
    this.data.backFromInputTextValuePageCb = () => {
      console.log(title, app.globalData.inputTextValuePage);
      this.setData({
        [key]: app.globalData.inputTextValuePage
      })

      app.globalData.inputTextValuePage = ""
    }
  },

  // 显示textarea
  showTextarea() {
    var that = this;
    that.setData({
      text: !that.data.text
    })
  },
  // 输入房源标题
  inputRoomTitle(e) {
    var that = this;
    let inputtitle = e.detail.value;
    if (inputtitle.length >= 30) {
      wx.showToast({
        icon: "none",
        duration: 2000,
        title: "30字内"
      })
      that.setData({
        essentialInfo: essentialInfo,
        isDisabled: false
      })
      return;
    }
    essentialInfo.title = inputtitle;
    that.setData({
      essentialInfo: essentialInfo,
    })
  },
  //手动输入撞楼
  inputlou(e) {
    var data = e.detail.value;
    this.setData({
      isResblcok: data
    })
  },

  floorNumberInputFocus(e) {
    return
    console.log("焦点focus====", e);

    if (this.data.floorNumberInputTime) {
      clearTimeout(this.data.floorNumberInputTime)
      this.data.floorNumberInputTime = null
      console.log("clear~~~");

    }

    // let bottom = this.data.floorNumberInputCount++ == 0 ? 200 : e.detail.height
    // console.log("bottom", bottom);

    this.setData({
      bottom: e.currentTarget.dataset.inputId == "1" ? 220 : e.detail.height
    })

  },

  floorNumberInputBlur(e) {
    return
    console.log("焦点blur====", e);
    if (this.data.floorNumberInputTime) {
      clearTimeout(this.data.floorNumberInputTime)
      this.data.floorNumberInputTime = null
      console.log("clear~~~");

    }
    this.data.floorNumberInputTime = setTimeout(() => {
      // this.data.floorNumberInputCount = 0
      this.setData({
        bottom: 0
      })
    }, 70)
  },

  inputdanyuan(e) {

    var data = e.detail.value;
    this.setData({
      isUnit: data
    })
  },
  inputlouceng(e) {
    var data = e.detail.value;
    this.setData({
      isFloor: data
    })
  },
  inputzonglou(e) {
    var data = e.detail.value;
    this.setData({
      zonglouceng: data
    })
  },
  inputmenpai(e) {
    var data = e.detail.value;
    this.setData({
      isRoom: data
    })
  },
  //五单元按钮
  selectnoDanyuan() {
    this.setData({
      isUnit: "无",
    })
  },

  // 弹窗切换
  toggleDialog(e) {
    var that = this;
    /*
     *state:
     *1. 楼
     *2.单元
     *3.
     */
    var state = e.currentTarget.dataset.state;
    console.log("toggleDialog====", state, typeof(state));

    if (state) {
      this.setData({
        //当前显示的哪个modal
        locationState: state
      });
      if (state > 0) {
        this.setData({
          showDialog: false
        });
      }
      //楼单元的各种请求
      switch (state) {
        //激动
        case "1":
          if (that.data.houDelId == "") {
            api.addHouseResblcok({
              resblockId: that.data.villageData.resblockId,
              hdResblockId: that.data.villageData.hdResblockId
            }, (res) => {
              if (res.data.isSuccess) {
                that.setData({
                  resblcok_all: res.data.content
                })
              }
            })
          } else {
            api.addHouseResblcok({
              hdResblockId: that.data.resblockId
            }, (res) => {
              if (res.data.isSuccess) {
                that.setData({
                  resblcok_all: res.data.content
                })
              }
            })
          }
          break;
          //请求机单元
        case "2":
          if (that.data.hdBuildingId == '') {
            var hdBuildingId = e.currentTarget.dataset.build.hdBuildingId || "";
            var buildingId = e.currentTarget.dataset.build.buildingId || "";
          } else {
            var hdBuildingId = that.data.hdBuildingId;
            var buildingId = that.data.buildingId;
          }
          api.addHouseUnit({
              hdBuildingId: hdBuildingId,
              buildingId: buildingId
            }, (res) => {
              if (res.data.isSuccess) {
                // if (res.data.content[0] != '无'){
                that.setData({
                    unit_all: res.data.content,
                    hdBuildingId: hdBuildingId,
                    buildingId: buildingId,
                    isResblcok: e.currentTarget.dataset.build.buildingNum,
                  })
                  // }
                if (res.data.content[0] == '无') {
                  that.setData({
                    locationState: 3
                  })
                  api.addHouseFloor({
                    hdBuildingId: that.data.hdBuildingId,
                    buildingId: that.data.buildingId,
                    unit: '无'
                  }, (res) => {
                    if (res.data.isSuccess) {
                      that.setData({
                        floor_all: res.data.content,
                        unit: '无',
                        isUnit: unit,
                      })
                    }
                  })
                }
              }
            })
            // var unit = e.currentTarget.dataset.unit || ""

          break;
          //楼层
        case "3":
          if (that.data.unit == '') {
            // console.log('初次进入')
            var unit = e.currentTarget.dataset.unit || ""
          } else {
            // console.log('返回进入')
            var unit = that.data.unit
          }
          api.addHouseFloor({
            hdBuildingId: that.data.hdBuildingId,
            buildingId: that.data.buildingId,
            unit: unit
          }, (res) => {
            if (res.data.isSuccess) {
              that.setData({
                floor_all: res.data.content,
                unit: unit,
                isUnit: unit,
              })
            }
          })

          break;
          //房间号
        case "4":
          var floor = e.currentTarget.dataset.floor || ""
          api.addHouseRoomNumber({
            hdBuildingId: that.data.hdBuildingId,
            buildingId: that.data.buildingId,
            unit: that.data.unit,
            floor: floor,
          }, (res) => {
            if (res.data.isSuccess) {
              if (that.data.houDelId != "") {
                var r = [];
                var room_all = res.data.content;
                room_all.forEach(item => r.push(item.roomNo))
                  // console.log(r)
                that.setData({
                  room_all: r,
                  isFloor: e.currentTarget.dataset.floor,
                })
              } else {
                that.setData({
                  room_all: res.data.content,
                  isFloor: e.currentTarget.dataset.floor,
                })
              }
            }
          })
          break;
          //房间号
        case "99":
          if (that.data.houDelId == "") {
            var roomNo = e.currentTarget.dataset.floor.roomNo;
          } else {
            console.log(e.currentTarget.dataset.floor)
            var roomNo = e.currentTarget.dataset.floor;
          }
          var hdHouseId = e.currentTarget.dataset.floor.hdHouseId;
          var houseId = e.currentTarget.dataset.floor.houseId;
          //这里需要去验证是否已经委托  // TODO:
          // houseId房源ID  hdHouseId  HD房源ID   delegationType  委
          var delegationType;
          var currentTabHeaderIndex = this.data.currentTabHeaderIndex
          if (currentTabHeaderIndex == 0) {
            delegationType = "SALES"
          } else if (currentTabHeaderIndex == 1) {
            delegationType = "RENT"
          } else {
            delegationType = "SALES|RENT"
          }
          api.addHouseisExistDel({
            houseId: null,
            hdHouseId: hdHouseId,
            delegationType: delegationType
          }, (res) => {
            console.log(JSON.stringify(res))
            if (res.data.isSuccess) {
              this.setData({
                showDialog: false,
                houseId: houseId,
                hdHouseId: hdHouseId,
                isRoom: roomNo,
                hdHouseId: hdHouseId,
              });
            } else {
              wx.showToast({
                icon: "none",
                duration: 3000,
                title: res.data.errorMessage
              })
              this.setData({
                showDialog: false
              });
              return;
            }
          })

          break;
          //手动创建
        case "1005":
          var that = this;

          var inputData = {
            resblockId: that.data.villageData.resblockId,
            hdResblockId: that.data.villageData.hdResblockId,
            buildingNum: that.data.isResblcok,
            totalFloor: that.data.zonglouceng,
            floor: that.data.isFloor,
            roomNo: that.data.isRoom,
            unit: that.data.isUnit,
          }
          var data = JSON.stringify(inputData)
          if (this.data.houDelId == "") {
            api.addCreateBuilding(data, (res) => {
              this.setData({
                showDialog: false,
                houseId: res.data.content.houseId
              })
            })
          } else {
            this.setData({
                showDialog: !this.data.showDialog,
              })
          }
          
          break;
        default:

      }

    }
    this.setData({
      showDialog: !this.data.showDialog,
      bottom: 0
    });
  },
  // 模式切换
  currentTabHeader(e) {
    this.setData({
      currentTabHeaderIndex: this.data.forbid == false ? e.currentTarget.dataset.index : this.data.currentTabHeaderIndex,
    })
    // console.log(this.data.currentTabHeaderIndex)
    if (this.data.currentTabHeaderIndex == 0 || this.data.currentTabHeaderIndex == 1) {
      wx.getStorageSync('currentStatus', this.data.currentTabHeaderIndex + 1)
    }
  },
  // 新增业主
  addOwner() {
    var addOwnerNum = this.data.addOwnerNum + 1;
    this.setData({
      addOwnerNum: addOwnerNum
    })
  },
  //减少业主
  reduceOwner() {
    if (this.data.addOwnerNum < 1)
      return;
    var addOwnerNum = this.data.addOwnerNum - 1;
    this.setData({
      addOwnerNum: addOwnerNum
    })
  },
  //售价选中
  salseFocus(e) {
    this.setData({
      salseFocus: true
    })
  },
  //售价输入
  inputSales(e) {
    var salse = e.detail.value;
    salse = formatDecimal(salse)
    console.log(salse);
    
    this.setData({
      salse: salse
    })
    if (this.data.houDelId != '') {
      this.data.essentialInfo.totalPrices = salse
    }
  },
  //室厅卫

  inputRoom(e) {
    var that = this;
    var room = e.currentTarget.dataset.room
    if (room == "from_input") {
      //清空已经选的室 并且将input得到的作为室
      let inputRoom = e.detail.value;
      if (that.data.houDelId != '') {
        essentialInfo.room = inputRoom;
        that.setData({
          shi: inputRoom,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        shi: inputRoom,
      })
    } else {
      if (that.data.houDelId != '') {
        essentialInfo.room = room;
        that.setData({
          shi: room,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        shi: room,
      })
    }

  },
  inputHall(e) {
    var that = this;
    var hall = e.currentTarget.dataset.hall
    if (hall == "from_input") {
      //清空已经选的室 并且将input得到的作为室
      let inputRoom = e.detail.value;
      if (that.data.houDelId != '') {
        essentialInfo.hall = inputRoom;
        that.setData({
          ting: inputRoom,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        ting: inputRoom,
      })
    } else {
      if (that.data.houDelId != '') {
        essentialInfo.hall = hall;
        that.setData({
          ting: hall,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        ting: hall,
      })
    }

  },
  inputToilet(e) {
    var that = this;
    var toilet = e.currentTarget.dataset.toilet
    if (toilet == "from_input") {
      //清空已经选的室 并且将input得到的作为室
      let inputRoom = e.detail.value;
      if (that.data.houDelId != '') {
        essentialInfo.toilet = inputRoom;
        that.setData({
          wei: inputRoom,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        wei: inputRoom,
      })
    } else {
      if (that.data.houDelId != '') {
        essentialInfo.toilet = toilet
        that.setData({
          wei: toilet,
          essentialInfo: essentialInfo
        })
      }
      that.setData({
        wei: toilet,
      })
    }
  },

  //鹈鹕

  inputTi(e) {
    var that = this;
    var ti = e.currentTarget.dataset.ti
    if (ti == "from_input") {
      //清空已经选的室 并且将input得到的作为室
      let inputRoom = e.detail.value;
      if (that.data.houDelId != '') {
        houseInfo.elevatorNum = inputRoom;
        that.setData({
          ti: inputRoom,
          houseInfo: houseInfo
        })
      }
      that.setData({
        ti: inputRoom,
      })
    } else {
      if (that.data.houDelId != '') {
        houseInfo.elevatorNum = ti;
        that.setData({
          ti: ti,
          houseInfo: houseInfo
        })
      }
      that.setData({
        ti: ti,
      })
    }
  },

  //输入聚焦

  foucus: function(e) {

    var that = this;
    console.log(e.detail.height)
    that.setData({

      bottom: e.detail.height

    })

  },

  //输入框押的值
  getValueYa(e) {
    var that = this;
    let inputYa = e.detail.value;
    that.setData({
      ya: inputYa
    })
  },
  //输入框付的值
  getValueFu(e) {
    var that = this;
    let inputFu = e.detail.value;
    that.setData({
      fu: inputFu
    })
  },

  //失去聚焦

  blur: function(e) {

    var that = this;

    that.setData({

      bottom: 0

    })

  },
  inputHu(e) {
    var that = this;
    var hu = e.currentTarget.dataset.hu
    if (hu == "from_input") {
      //清空已经选的室 并且将input得到的作为室
      let inputRoom = e.detail.value;
      if (that.data.houDelId != '') {
        houseInfo.roomNum = inputRoom;
        that.setData({
          hu: inputRoom,
          houseInfo: houseInfo
        })
      }
      that.setData({
        hu: inputRoom,
      })
    } else {
      if (that.data.houDelId != '') {
        houseInfo.roomNum = hu;
        that.setData({
          hu: hu,
          houseInfo: houseInfo
        })
      }
      that.setData({
        hu: hu,
      })
    }
  },

  //面积选择
  areaFocus(e) {
    this.setData({
      areaFocus: true
    })
  },
  //面积输入
  inputArea(e) {
    var that = this;
    let inputArea = e.detail.value;
    that.setData({
      // area: inputArea.replace(/[^0-9.]/g, '')
      area: formatDecimal(inputArea)
    })
    if (that.data.houDelId != '') {
      that.data.essentialInfo.buildSize = inputArea
    }
  },
  //房源标题
  inputRoomTitle(e) {
    var that = this;
    let inputtitle = e.detail.value;
    if (inputtitle.length >= 30) {
      wx.showToast({
        icon: "none",
        duration: 2000,
        title: "30字内"
      })
      essentialInfo.title = that.data.roomtitle;
      that.setData({
        essentialInfo: essentialInfo,
        roomtitle: that.data.roomtitle,
        titleNum: inputtitle.length
      })
      return;
    }
    essentialInfo.title = inputtitle;
    that.setData({
      essentialInfo: essentialInfo,
      roomtitle: inputtitle,
      titleNum: inputtitle.length
    })
  },
  //租金选择
  rentFocus(e) {
    this.setData({
      rentFocus: true
    })
  },

  //租金输入
  inputRent(e) {
    var that = this;
    let input = e.detail.value;
    if (that.data.houDelId != "" && that.data.currentTabHeaderIndex == 1) {
      that.data.essentialInfo.totalPrices = input
    }
    // else if (that.data.houDelId != "" && that.data.currentTabHeaderIndex == 2){
    //   that.data.essentialInfo.rent = input
    // }
    that.setData({
      rentmoney: input,
    })
  },


  //房源详情
  onpressHouseType(e) {
    // var that =this;
    var type = e.currentTarget.dataset.type;
    var data = e.currentTarget.dataset.housetype
    switch (type) {
      //房屋类型
      case "housetype":
        if (this.data.houDelId != '') {
          houseInfo.buildType = data;
          this.setData({
            houseType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
            houseType: data,
          })
          // console.log(that.data)
        break;
        //产权性质
      case "chanquanType":
        if (this.data.houDelId != '') {
          houseInfo.propetyType = data;
          this.setData({
            chanquanType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          chanquanType: data,
        })
        break;
        // 朝向
      case "chaoxiangType":
        console.log("设置房源朝向", data);
        
        this.setData({
          chaoxiangType: data,
        })
        break;
        // 楼层
      case "loucenType":
        console.log("设置楼层了", data);
        this.setData({
          loucenType: data,
        })
        break;
        //贷款
      case "daikuanType":
        if (this.data.houDelId != '') {
          houseInfo.loanInfo = data;
          this.setData({
            daikuanType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          daikuanType: data,
        })
        break;
        //学位
      case "xueweiType":
        if (this.data.houDelId != '') {
          houseInfo.schoolOccupy = data;
          this.setData({
            xueweiType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          xueweiType: data,
        })
        break;
        //装修
      case "zhuangxiuType":
        if (this.data.houDelId != '') {
          houseInfo.decorateType = data;
          this.setData({
            zhuangxiuType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          zhuangxiuType: data,
        })
        break;
        //看房时间
      case "kanfangType":
        if (this.data.houDelId != '') {
          houseInfo.approTime = data;
          this.setData({
            kanfangType: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          kanfangType: data,
        })
        break;
        //出售标签
      case "chushouType":
        let chushouType = this.data.chushouType || []
        if (chushouType.indexOf(data) > -1) {
          //存在就删
          for (var i = 0; i < chushouType.length; i++) {
            if (chushouType[i] == data)
              chushouType.splice(i, 1);
          }
        } else {
          chushouType.push(data)
        }
        if (this.data.houDelId != '' && this.data.currentTabHeaderIndex == 2) {
          essentialInfo.salesTag = chushouType;
          this.setData({
            chushouType: chushouType,
            essentialInfo: essentialInfo
          })
        } else {
          this.setData({
            chushouType: chushouType,
          })
        }

        break;
        //出租标签
      case "chuzuType":
        let chuzuType = this.data.chuzuType;

        // let chuzuType;
        if (chuzuType.indexOf(data) > -1) {
          for (var j = 0; j < chuzuType.length; j++) {
            console.log(chuzuType)
            if (chuzuType[j] == data)
              chuzuType.splice(j, 1);
          }
        } else {
            // chuzuType = [];
            // var aar = [];
            // chuzuType.push(data)
          if (this.data.houDelId != '' && this.data.currentTabHeaderIndex == 2) {
            aar.push(data)
          } else {
            chuzuType.push(data)
          }
        }
        if (this.data.houDelId != '' && this.data.currentTabHeaderIndex == 2) {
          essentialInfo.rentTag = aar;
          this.setData({
            chuzuType: aar,
            essentialInfo: essentialInfo
          })
        } else {
          this.setData({
            chuzuType: chuzuType,
          })
        }

        break;
        //租金
      case "yaType":
        if (this.data.houDelId != '') {
          houseInfo.fkfsy = data;
          this.setData({
            ya: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          ya: data,
        })
        break;
        //租金
      case "fuType":
        if (this.data.houDelId != '') {
          houseInfo.fkfsf = data;
          this.setData({
            fu: data,
            houseInfo: houseInfo
          })
        }
        this.setData({
          fu: data,
        })
        break;
      
      //亮点
      case "lightSpot":
        let lightSpot = this.data.lightSpot || []
        if (lightSpot.indexOf(data) > -1) {
          //存在就删
          for (var i = 0; i < lightSpot.length; i++) {
            if (lightSpot[i] == data)
              lightSpot.splice(i, 1);
          }
        } else {
          lightSpot.push(data)
        }
        
        // 保证与原先顺序一致
        lightSpot.sort((a, b) => {
          return lightSpotType.findIndex((v) => v.value == a) - lightSpotType.findIndex((v) => v.value == b)
        })

        this.setData({
          lightSpot: lightSpot,
        })

        break;
      default:
    }
  },
  //清空房源详情
  clearHouseType() {
    essentialInfo.salesTag = [];
    essentialInfo.rentTag = [];
    essentialInfo.tag = [];
    houseInfo.decorateType = '';
    houseInfo.buildType = '';
    houseInfo.propetyType = '';
    houseInfo.loanInfo = '';
    houseInfo.schoolOccupy = '';
    houseInfo.approTime = '';
    this.setData({
      essentialInfo: essentialInfo,
      houseInfo: houseInfo,
      houseType: '',
      chanquanType: '',
      chaoxiangType: '',
      buildNumNew: '',
      loucenType: '',
      daikuanType: '',
      xueweiType: "",
      kanfangType: '',
      chushouType: [],
      lightSpot: [],
      chuzuType: [],
      zhuangxiuType: ""
    })
  },

  //选择图片--立即上传获取----
  chooseimage: function() {
    var that = this;
    util.updateImages(10, function(res) {
      let filePathArr = res.tempFilePaths;
      filePathArr.forEach(item => {
        util.uploadFiles(item, function(res) {
          console.log("上传图片成功====", res);
          try {
            var id = JSON.parse(res.data)[0].id;
            var newtempFilePathsObj = {
              fileId: id,
              houDelId: that.data.houDelId,
              tagCode: "",
              tagName: "未选择",
              // cover: false,
              cover: 1,
              url: item
            }
            var imgArrayObj = that.data.imgArray;
            if (imgArrayObj.length > 11) {
              wx.showToast({
                icon: "none",
                duration: 2000,
                title: "最多12张"
              })
            } else {
              imgArrayObj.push(newtempFilePathsObj)
              that.setData({
                imgArray: imgArrayObj
              })
              that.selectComponent('#drag').dataChange();
            }
            
          } catch (error) {
            
          }
        })
      })

    })

  },
  //选择视频
  chooseVideo() {
    var that = this;
    wx.chooseVideo({
      //相机和相册
      sourceType: ['album', 'camera'],
      //录制视频最大时长
      maxDuration: 60,
      //摄像头
      camera: ['front', 'back'],
      //这里返回的是tempFilePath
      success: function(res) {
        that.data.videoArray.push(res.tempFilePath);
        that.setData({
          videoArray: that.data.videoArray,
        })
      },
      fail: function(e) {}
    })
  },
  // 获取房源信息
  getHouseInfo() {
    const that = this;
    api.getHouseInfo({
        houDelId: that.data.houDelId
      }, (res) => {
        const content = res.data.content;
        if (this.data.isScan) {
          wx.gio('track', constant.SCAN_SUCCESS, {      
            [constant.ROOMTYPE_VAR]: content.houDelVO.delegationType == "SALES" ? constant.ER_SHOU : constant.CHU_ZU,
          })
        }
        that.checksubscribe({
          subscribeJumpTag: content.houDelVO.delegationType ? content.houDelVO.delegationType.toLowerCase() : '',
          subscribeName: content.houDelVO.resblockName,
          subscribeId: content.houDelVO.hdResblockId,
          subscribeCityCode: content.houDelVO.cityCode,
        })
        essentialInfo = {
          id: content.houDelVO.id,
          title: content.houDelVO.title,
          tag: content.houDelVO.tag,
          lightSpot: content.houDelVO.lightSpot || [],
          totalPrices: content.houDelVO.totalPrices != -1 ? (content.houDelVO.delegationType == "SALES" ? content.houDelVO.totalPrices / 10000 : content.houDelVO.totalPrices) : '',
          room: content.houDelVO.room != -1 ? content.houDelVO.room : '',
          hall: content.houDelVO.hall != -1 ? content.houDelVO.hall : '',
          toilet: content.houDelVO.toilet != -1 ? content.houDelVO.toilet : '',
          buildSize: content.houDelVO.buildSize != -1 ? content.houDelVO.buildSize : ''
        }
        houseInfo = {
          id: content.houDelVO.id,
          elevatorNum: content.houDelVO.elevatorNum != -1 ? content.houDelVO.elevatorNum : '',
          roomNum: content.houDelVO.roomNum != -1 ? content.houDelVO.roomNum : '',
          buildType: content.houDelVO.buildType,
          propetyType: content.houDelVO.propetyType,
          loanInfo: content.houDelVO.loanInfo,
          schoolOccupy: content.houDelVO.schoolOccupy,
          approTime: content.houDelVO.approTime,
          decorateType: content.houDelVO.decorateType,
        }
        that.setData({
          chaoxiangType: content.houDelVO.direction || "" ,
          loucenType: content.houDelVO.buildNumNew || "" ,
          shi: content.houDelVO.room,
          detailContent: content,
          imgArray: content.houImageVO, //房源图片
          essentialInfo: essentialInfo, //基本信息
          houseInfo: houseInfo, //房源信息
          zhuangxiuType: content.houDelVO.decorateType,
          houseType: content.houDelVO.buildType,
          chanquanType: content.houDelVO.propetyType,
          daikuanType: content.houDelVO.loanInfo,
          xueweiType: content.houDelVO.schoolOccupy,
          kanfangType: content.houDelVO.approTime,
          _houseTitle: content.houDelVO.title,
          _sellPoint: (content.houDelRecommendVO && content.houDelRecommendVO.sellingPoint && content.houDelRecommendVO.sellingPoint.context) || "",
          _ownerState: (content.houDelRecommendVO && content.houDelRecommendVO.ownerPsychology && content.houDelRecommendVO.ownerPsychology.context) || "",
          _service: (content.houDelRecommendVO && content.houDelRecommendVO.service && content.houDelRecommendVO.service.context) || "",

          _houseType: (content.houDelRecommendVO && content.houDelRecommendVO.houseType && content.houDelRecommendVO.houseType.context) || "",
          _trafficResolve: (content.houDelRecommendVO && content.houDelRecommendVO.trafficResolve && content.houDelRecommendVO.trafficResolve.context) || "",
          _surroundMating: (content.houDelRecommendVO && content.houDelRecommendVO.surroundMating && content.houDelRecommendVO.surroundMating.context) || "",
          _decoration: (content.houDelRecommendVO && content.houDelRecommendVO.decoration && content.houDelRecommendVO.decoration.context) || "",
          _resblockIntroduce: (content.houDelRecommendVO && content.houDelRecommendVO.resblockIntroduce && content.houDelRecommendVO.resblockIntroduce.context) || "",

          vr: content.hmDelSummaryInfo.houSubType==1 && content.hmDelSummaryInfo.houSubTypeState!= 10 && content.hmDelSummaryInfo.houSubTypeState!= 1 ? true : false
        })
        that.selectComponent('#drag').dataChange();
        if (that.data.detailContent.houDelVO.delegationType == "SALES") {
          var currentTabHeaderIndex = 0
        } else if (that.data.detailContent.houDelVO.delegationType == "RENT") {
          var currentTabHeaderIndex = 1
        } else {
          var currentTabHeaderIndex = 2
        }

        that.setData({
          currentTabHeaderIndex: currentTabHeaderIndex,
          isResblcok: that.data.detailContent.houDelVO.buildingNum,
          isUnit: that.data.detailContent.houDelVO.unit,
          isFloor: that.data.detailContent.houDelVO.floor != -1 ? that.data.detailContent.houDelVO.floor : '',
          zonglouceng: that.data.detailContent.houDelVO.totalFloor || '',
          isRoom: that.data.detailContent.houDelVO.roomNO,
          salse: that.data.detailContent.houDelVO.delegationType == "SALES" && that.data.essentialInfo.totalPrices != -0.0001 ? that.data.essentialInfo.totalPrices : "",
          shi: that.data.essentialInfo.room,
          ting: that.data.essentialInfo.hall,
          wei: that.data.essentialInfo.toilet,
          ti: that.data.houseInfo.elevatorNum,
          hu: that.data.houseInfo.roomNum,
          area: that.data.essentialInfo.buildSize,
          chushouType: that.data.detailContent.houDelVO.delegationType == "SALES" ? that.data.essentialInfo.tag : [],
          lightSpot: that.data.essentialInfo.lightSpot,
          zhuangxiuType: that.data.essentialInfo.decorateType,
          houseType: that.data.essentialInfo.buildType,
          chanquanType: that.data.essentialInfo.propetyType,
          daikuanType: that.data.essentialInfo.loanInfo,
          xueweiType: that.data.essentialInfo.schoolOccupy,
          kanfangType: that.data.essentialInfo.approTime,
          chuzuType: that.data.detailContent.houDelVO.delegationType == "RENT" && that.data.detailContent.houDelVO.tag != null ? that.data.essentialInfo.tag : [],
          ya: that.data.detailContent.houDelVO.fkfsy != -1 ? that.data.detailContent.houDelVO.fkfsy : '',
          fu: that.data.detailContent.houDelVO.fkfsf != -1 ? that.data.detailContent.houDelVO.fkfsf : '',
          rentmoney: that.data.detailContent.houDelVO.delegationType == "RENT" ? that.data.essentialInfo.totalPrices : "",
        })
        // 如果是vr房源的话先更新下权限
        if(that.data.vr){
          api.getMemberPower({},(res) => {
            if(res.data.isSuccess){
              wx.setStorageSync('memberInfo', res.data.content.rows)
              
            }
          })
        }
      })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
//     flag: "0"
// houDelId: "ce554c638ed14ae98da59350afc05e34"
    console.log('================', options);
    
    app.globalData.loginPromise.then(() => {
      if(options.flag){
        this.setData({
          flag: 0
        })
      }
      if(options.subscribe){
        this.setData({
          subscribe: true
        })
      }
      if (options.villageData) {
        var villageData = JSON.parse(options.villageData)
        console.log("房源录入==", villageData)
        this.setData({
          villageData: villageData,
          currentTabHeaderIndex: wx.getStorageSync('currentStatus') - 1
        })
        wx.setNavigationBarTitle({
          title: villageData.resblockName,
        })
      } else if (options.houDelId) {
        // this.data.isScan = options.isScan ? true:false
        this.setData({
          isScan: options.isScan
        })
        wx.setNavigationBarTitle({
          title: '房源信息修改',
        })
        api.delDelegationTypeAndResblockId({
          houDelId: options.houDelId,
        }, res => {
          // console.log(res.data.content.length)
          this.setData({
            resblockId: res.data.successMessage
          })
          if (res.data.content.length == 2) {
            this.setData({
              forbid: true,
            })
          }
        })
        this.setData({
          houDelId: options.houDelId
        })
        this.getHouseInfo();
      
      }
    })
  },
  //跳转到图片标签选择
  chooseTag(e) {
    var key = e.detail.newKey;
    var imgArray = this.data.imgArray;
    wx.navigateTo({
      url: '/pages/addHouse/chooseTag/chooseTag?imgArray=' + JSON.stringify(imgArray) + "&key=" + key,
    })
  },
  chooseVideoTag() {
    wx.navigateTo({
      url: '/pages/addHouse/chooseVideoTag/chooseVideoTag',
    })
  },
  //保存 未填写 toast
  toastMsg(types) {
    wx.showToast({
      icon: "none",
      duration: 5000,
      title: `请补充房源${types}信息`,
    })
    return; 
  },
  // 保存房源信息
  saveHouseInfo() {
    var that = this;
    let imgArray = that.data.imgArray;
    if (imgArray.length > 0) {
      imgArray.forEach((item,index)=> item.cover = index)
    }
    var allPostData = {
      userId: that.data.userId,
      storeId: that.data.storeId,
      houseId: that.data.houseId,
      hdHouseId: that.data.hdHouseId,
      addr: that.data.villageData.addr,
      delegationType: that.data.delegationType,
      room: that.data.shi,
      hall: that.data.ting,
      toilet: that.data.wei,
      elevatorNum: that.data.ti,
      roomNum: that.data.hu,
      buildSize: that.data.area,
      buildType: that.data.houseType,
      schoolOccupy: that.data.xueweiType,
      propertyRight: {
        propetyType: that.data.chanquanType,
        loanInfo: that.data.daikuanType,
      },
      unit: that.data.isUnit,
      floor: that.data.isFloor,
      totalFloor: that.data.zonglouceng,
      roomNo: that.data.isRoom,
      del: {
        title: this.data._houseTitle || that.data.villageData.resblockName + " " + (that.data.shi != '' ? (that.data.shi + '室') : '') + (that.data.ting != '' ? (that.data.ting + '厅') : '') + (that.data.wei != '' ? (that.data.wei + '卫') : ''),
        totalPrices: that.data.salse,
        rent: that.data.rentmoney,
        fkfsf: that.data.fu,
        fkfsy: that.data.ya,
        approTime: that.data.kanfangType,
        salesTag: that.data.chushouType,
        rentTag: that.data.chuzuType,
        decorateType: that.data.zhuangxiuType,
        // buildFloor: that.data.loucenType,  //楼层 （前端后端的字段不一样）
      },
      lightSpot: that.data.lightSpot,
      direction: that.data.chaoxiangType, //朝向
      buildNumNew: that.data.loucenType, //楼层（新）
      imgs: imgArray
    }

    // 保存房源后再 保存 房源的卖点
    api.addHouseSaveNew(JSON.stringify(allPostData), (res) => {
      this.data.isCreatingBuilding = false;
      if (res.data.isSuccess) {
        that.setData({
          successModal: false,
          successId: res.data.content,
          sureDownVr: true
        })

        // 租
        if (allPostData.delegationType == "RENT") {

        } else {
          this.saveHouDelRecommendVO(res.data.content, allPostData.delegationType)
        }

        let detail = []
          .concat(allPostData.del.approTime)
          .concat(allPostData.del.decorateType)
          .concat(allPostData.del.rentTag)
          .concat(allPostData.del.salesTag)
          .concat(allPostData.direction)
          .concat(allPostData.propertyRight.loanInfo)
          .concat(allPostData.propertyRight.propetyType)
          .concat(allPostData.schoolOccupy)
          .concat(allPostData.buildType)
          .filter(v => !!v)
          .join("、")

        wx.gio('track', constant.ENTRY_ROOM_SUCCESS, { 
          [constant.ROOMTYPE_VAR]: ({
            "SALES": constant.ER_SHOU,
            "RENT": constant.CHU_ZU,
            "SALES|RENT": constant.ZU_SHOU,
          })[allPostData.delegationType],
          [constant.SALEPRICE_VAR]: allPostData.del.totalPrices,
          [constant.HUXING_VAR]: `${allPostData.room}室${allPostData.hall}厅${allPostData.toilet}卫`,
          [constant.TIHU_VAR]: `${allPostData.elevatorNum}梯${allPostData.roomNum}户`,
          [constant.AREA_VAR]: allPostData.buildSize + '㎡',
          [constant.ROOMTITLE_VAR]: allPostData.del.title,
          [constant.SALEPOINT_VAR]: that.data._sellPoint,
          [constant.XINTAI_VAR]: that.data._ownerState,
          [constant.RENTPRICE_VAR]: allPostData.del.rent,
          [constant.PAYWAY_VAR]: `押${allPostData.del.fkfsy}付${allPostData.del.fkfsf}`,
          [constant.PICNUM_VAR]: allPostData.imgs.length,
          [constant.ADDRESS_VAR]: `${that.data.isResblcok}栋${allPostData.floor}楼${allPostData.roomNo}号`,
          [constant.ROOMDETAIL_VAR]: detail,
        })

      } else {
        wx.showToast({
          icon: "none",
          duration: 8000,
          title: "提交错误"
        })
      }

      var currentCity = wx.getStorageSync('currentCity');
      insertHouseLog({
        logType: "4",
        cityName: currentCity? currentCity.city : "上海市",
        inputHouseType: that.data.delegationType,
        createResult: res.data.isSuccess ? 0 : 1,
        delId: res.data.content
      })
    })
  },

  //保存房源
  saveRoom() {
    if (!this.data.canPubilish) return;
    if (this.data.isCreatingBuilding) {
      return wx.showToast({ title: `操作过于频繁!`, icon: "none", })
    }
    // debugger
    var delegationType;
    var currentTabHeaderIndex = this.data.currentTabHeaderIndex
    if (currentTabHeaderIndex == 0) {
      delegationType = "SALES"
    } else if (currentTabHeaderIndex == 1) {
      delegationType = "RENT"
    } else {
      delegationType = "SALES|RENT"
    }

    var that = this;
    // 没有设置房源信息的情况夏获取houseid
    let storeId = getApp().globalData.loginUserInfo.data.content.sessionUser.extProps.storeId;
    let userId = getApp().globalData.loginUserInfo.data.content.sessionUser.id;
    that.setData({
      userId: userId,
      storeId: storeId,
      delegationType: delegationType
    })
    if (that.data.houseId != "" || that.data.hdHouseId != "") {
      that.saveHouseInfo()
      return
    }
    var inputData = {
      resblockId: that.data.villageData.resblockId,
      hdResblockId: that.data.villageData.hdResblockId,
      buildingNum: that.data.isResblcok,
      totalFloor: that.data.zonglouceng,
      floor: that.data.isFloor,
      roomNo: that.data.isRoom,
      unit: that.data.isUnit,
    }
    var data = JSON.stringify(inputData)

    this.data.isCreatingBuilding = true;
    api.addCreateBuilding(data, (res) => {
        that.setData({
            showDialog: false,
            houseId: res.data.content.houseId
          })
        that.saveHouseInfo()
      })
    
  },
  // 更新图片
  updateImage() {
    var that = this;
    var imgArray = that.data.imgArray;
    if (imgArray.length > 0) {
      imgArray.forEach((item, index) => { item.cover = index })
        // imgArray[0].cover="0";
    }
    api.updateImage({
      houImgList: imgArray
    }, (res) => {
     
    })
  },

  // 更新房源信息 
  updateDelInfo() {
    p.showLoading({ title: '保存中', })

    var that = this;
    // essentialInfo.totalPrices
    let _totalPrices = that.data.currentTabHeaderIndex != 1 ? (essentialInfo.totalPrices != '' ? essentialInfo.totalPrices * 10000 : '') : (essentialInfo.totalPrices != '' ? essentialInfo.totalPrices : '');

    houseInfo.buildingNum = that.data.isResblcok;
    houseInfo.totalFloor = that.data.zonglouceng;
    houseInfo.floor = that.data.isFloor;
    houseInfo.room_no = that.data.isRoom;
    houseInfo.unit = that.data.isUnit;

    essentialInfo.lightSpot = that.data.lightSpot;

    if (that.data.currentTabHeaderIndex == 0) {
      var updelegationType = "SALES";
      essentialInfo.tag = that.data.chushouType;
      houseInfo.delegationType = updelegationType;
    } else if (that.data.currentTabHeaderIndex == 1) {
      var updelegationType = "RENT";
      essentialInfo.tag = that.data.chuzuType;
      houseInfo.delegationType = updelegationType;

      if (this.data.ya) {
        houseInfo.fkfsy = this.data.ya
      }
      if (this.data.fu) {
        houseInfo.fkfsf = this.data.fu
      }

    } else {
      houseInfo.delegationType = that.data.detailContent.houDelVO.delegationType;
      essentialInfo.rent = that.data.rentmoney;
      delete essentialInfo.tag;
      houseInfo.flag = '1'

      if (this.data.ya) {
        houseInfo.fkfsy = this.data.ya
      }
      if (this.data.fu) {
        houseInfo.fkfsf = this.data.fu
      }
    }

    var obj = Object.assign({}, essentialInfo, houseInfo)
    obj.totalPrices = _totalPrices
      // 房源标题
    obj.title = this.data._houseTitle
    obj.direction = this.data.chaoxiangType
    obj.buildNumNew = this.data.loucenType

    let fn = () => {
      return new Promise((resolve, reject) => {
        var houDelStr = JSON.stringify(obj);
        api.updateDelInfo({
          houDelStr: houDelStr
        }, (res) => {
          resolve()
  
          p.hideLoading()
          // if(this.data.vr&&this.data.vrDown&&this.data.vrDown.length!=0&&this.data.flag){
          // if(this.data.vr&&this.data.flag&&this.data.vrDown.length==0&&this.data.vrDown){
          if(this.data.vr&&this.data.flag&&this.data.vrDown&&!this.data.goCentre){
          // if(this.data.flag&&this.data.vrDown&&!this.data.goCentre){
            this.setData({
              successModal: false,
              sureDownVr: true,
              memberOption: false,
              successId: this.data.houDelId,
            })
          }else if (this.data.flag&&this.data.vrDown&&!this.data.goCentre){
            this.setData({
              successModal: false,
              sureDownVr: true,
              memberOption: false,
              successId: this.data.houDelId,
              vrDown: false,
            })
          }else if((this.data.memberOption&&this.data.vrDown.length==0&&this.data.statue!=0&&this.data.totalNumber <= 0)||this.data.goCentre){
              wx.redirectTo({
                url: '/pages/mine/memberCentre/memberCentre',
              })
          }else {
            if(this.data.isScan){
              this.setData({
                successModal: false,
                sureDownVr: true,
                memberOption: false,
                successId: this.data.houDelId,
              })
            }else{
              wx.navigateBack({
                delta: 1
              })
            }
    
          }
        })
      })
    }

    // 保存房源卖点 在 更新
    this.saveHouDelRecommendVO(this.data.houDelId, obj.delegationType)
      .then(() => {
        return fn()
      })
      .then(() => {
        api.examineDelPushAble({ delId: this.data.houDelId })
      })
  },

  // 保存核心卖点 业主心态等信息
  saveHouDelRecommendVO(houDelId, delegationType) {
    return new Promise((resolve, reject) => {
      const recommendInfo = {
        // deleted: delegationType == "RENT",
        deleted: false,
        houDelId,
        sellingPoint: {
          tag: "核心卖点",
          context: this.data._sellPoint
        },
        ownerPsychology: {
          tag: "业主心态",
          context: this.data._ownerState
        },
        service: {
          tag: "税费解析",
          context: this.data._service
        },
        houseType: {
          tag: "户型介绍",
          context: this.data._houseType
        },
        trafficResolve: {
          tag: "交通出行",
          context: this.data._trafficResolve
        },
        surroundMating: {
          tag: "周边配套",
          context: this.data._surroundMating
        },
        decoration: {
          tag: "装修描述",
          context: this.data._decoration
        },
        resblockIntroduce: {
          tag: "小区介绍",
          context: this.data._resblockIntroduce
        },
      }
      api.updateRecommendInfo({
        houDelRecStr: JSON.stringify(recommendInfo)
      }, (res) => {
        resolve()
      })
    })
  },
  // 查询是否有下载的权限
  handleMemberDownLoadImgs(e){
    let menuId = e.currentTarget.dataset.id;

    menuHandler
      .call(this, menuId)
      .then((downLoadImgs) => {
        this.setData({
          releaseNumber: downLoadImgs.dayNumber,
          totalNumber: downLoadImgs.totalNumber,
          menuId,
          dayNumbered: downLoadImgs.dayNumbered,
          totalNumbered: downLoadImgs.totalNumbered,
          statue: downLoadImgs.statue,
        })
        this.getMemberPower()
        this.setData({
          successModal: false,
          sureDownVr: true,
        })
      })
      .catch(() => {})
  },
  handleHideMoreOptions(){
    this.setData({
      memberOption:false,
      successModal: true,
      vrDown: [],
      items: [
        {value: '下载房源的VR',checked: false}
      ]
    })
  },
   // 去充值页面
   goToMemberCentre(e){
     if(e.currentTarget.dataset.gocentre==1){
       this.setData({
         goCentre: true
       })
     }
    this.setData({
      vrDown: [],
      items: [
        {value: '下载房源的VR',checked: false}
      ]
    })
    this.updateRoom();
  },
  getMemberPower(){
        api.submitVrTask({
          delId: this.data.houDelId
        }, (res) => {
          api.getMemberPower({menuId: this.data.menuId},(res) => {
            if(res.data.isSuccess){
              wx.setStorageSync('memberInfo', res.data.content.rows)
            }
          })
          if(res.data.isSuccess){
            this.updateRoom();
          }else {
            wx.showToast({
              title: 'VR关联失败，请取消对VR的勾选',
              icon: 'none'
            })
            return
          }
        })
  },
  // 下载VR
  submitVrTask(e){
    if (!this.data.canPubilish) return;
    
    return new Promise((resolve, reject) => {
      if(this.data.vrDown&&this.data.vrDown.length!=0){
        console.log('baocun1')
        this.handleMemberDownLoadImgs(e)
      }else {
        console.log('baocun2')
        this.updateRoom();
      }
    })
  },
  checkboxChange(e){
    const items = this.data.items
    const values = e.detail.value
    for (let i = 0, lenI = items.length; i < lenI; ++i) {
      items[i].checked = false

      for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (items[i].value === values[j]) {
          items[i].checked = true
          break
        }
      }
    }
    this.setData({
      vrDown: e.detail.value
    })
    console.log(e)
  },

  // 更新房源
  updateRoom() {
    if (!this.data.canPubilish) return;
    this.updateImage()
      // this.updateBaseInfo()
    this.updateDelInfo()
      // wx.navigateBack({
      //   delta: 1
      // })
  },
  goHome() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  //继续录入
  goContinue() {
    wx.navigateBack({
      delta: 1
    });
  },
  //分享房源
  goDetail(e) {
    const houdelid = this.data.successId;
    if (!houdelid) return
    /*
      from :true false代表是从录入进去
     */
    if(this.data.subscribe){
      wx.setStorageSync("houdelid", '3'); //1 分享房源 2 查看房源 3 新上房源
    } else {
      wx.setStorageSync("houdelid", '1'); //1 分享房源 2 查看房源 3 新上房源
    }
    wx.redirectTo({
      url: '/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=' + houdelid + "&from=0",
    })
  },
  //查看房源
  goDetails(e) {
    const houdelid = this.data.successId;
    if (!houdelid) return
    /*
      from :true false代表是从录入进去
     */
    if(!this.data.subscribe){
      wx.setStorageSync("houdelid", '2'); //1 分享房源 2 查看房源
    }
    wx.redirectTo({
      url: '/pages/house/RentalHouseDetail/RentalHouseDetail?houdelid=' + houdelid + "&from=0",
    })
  },
  change(e) {
    this.setData({
      imgArray: e.detail.imgArray
    });
  },
  toggleFixed(e) {
    let key = e.currentTarget.dataset.key;

    let {
      imgArray
    } = this.data;

    imgArray[key].fixed = !imgArray[key].fixed

    this.setData({
      imgArray: imgArray
    });

    console.log("imgArray====", imgArray);
    

    this.selectComponent('#drag').dataChange();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(e) {
    var that = this;

    if (this.data.backFromInputTextValuePageCb) {
      this.data.backFromInputTextValuePageCb()
      this.data.backFromInputTextValuePageCb = null
    } else {

      if (that.data.houDelId == "") {
        api.addHouseResblcok({
          resblockId: that.data.villageData.resblockId,
          hdResblockId: that.data.villageData.hdResblockId
        }, (res) => {
          if (res.data.isSuccess) {
            that.setData({
              resblcok_all: res.data.content
            })
          }
        })
      } else {
        // api.
      }
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
    let index = this.data.currentTabHeaderIndex
    if (index == 2) index = 0

    var that = this;
    var pages = getCurrentPages();
    var prevPage = pages[pages.length - 2]; //上一个页面
    if (prevPage && prevPage.setData) {
      prevPage.setData({
        isUpdate: true
      })
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  checksubscribe({
    subscribeId,
    subscribeName,
    subscribeCityCode,
    subscribeJumpTag
  }) {
    api.checksubscribe({hdResblockId: subscribeId}, (res) => {
      this.setData({
        subscribeJumpTag,
        subscribeCityCode,
        subscribeName: subscribeName,
        subscribeId: subscribeId,
        hasSubscribeStatus: true,
      })
      if(res && res.data && res.data.content && res.data.content > 0) {
        this.setData({
          isSubscribe: true,
        })
      }
    })
  },

  onSubscribeSuccess() {
    this.setData({
      isShowDialogSubscribe: true
    })
  },

  goSubscribe() {
    wx.redirectTo({
      url: `/pages/home/subscribe/myList/myList?id=${this.data.subscribeId}&name=${this.data.subscribeName}&citycode=${this.data.subscribeCityCode}&tab=${this.data.subscribeJumpTag}`,
    })
  }

})